var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const mysql2 = require("mysql2")
const cors = require('cors')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');



const pool = mysql2.createPool(getDBConfig()); //创建数据库连接池

var app = express();
app.set('pool', pool); //将连接池挂载到app上
//微信小程序
var shop_wx_user = require('./routes/server_wx/user')(app.get('pool'));
var shop_wx_news = require('./routes/server_wx/news')(app.get('pool'));
var shop_wx_shop = require('./routes/server_wx/shop')(app.get('pool'));
var shop_wx_orders = require('./routes/server_wx/orders')(app.get('pool'));
//后台管理系统
var shop_sys_user = require('./routes/server_sys/sys_user')(app.get('pool'));
var shop_sys_classify = require('./routes/server_sys/sys_classify')(app.get('pool'));
var shop_sys_orders = require('./routes/server_sys/sys_orders')(app.get('pool'));
var shop_sys_goods = require('./routes/server_sys/sys_goods')(app.get('pool'));
var shop_sys_review = require('./routes/server_sys/sys_review')(app.get('pool'));
var shop_sys_new = require('./routes/server_sys/sys_new')(app.get('pool'));
var shop_sys_admin = require('./routes/server_sys/sys_admin')(app.get('pool'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


app.use(cors())
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
//微信小程序api
app.use('/user', shop_wx_user);
app.use('/news', shop_wx_news);
app.use('/shop', shop_wx_shop);
app.use('/orders', shop_wx_orders);
//后台api
app.use('/sysuser', shop_sys_user);
app.use('/sysclassify', shop_sys_classify);
app.use('/sysorders', shop_sys_orders);
app.use('/sysgoods', shop_sys_goods);
app.use('/sysreview', shop_sys_review);
app.use('/sysnew', shop_sys_new);
app.use('/sysadmin', shop_sys_admin);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


//进程崩溃，关闭数据库连接
process.on('SIGINT', () => {
  pool.end();
  process.exit(0);
})


//数据库配置
function getDBConfig(){
  return {
      host:'127.0.0.1',
      port:3306,
      user:"root",
      password:"",
      database:"c_shop",
      connectionLimit:100
  }
}
module.exports = app;
